<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{PlatClass, BusinessCommu, BussinessLog, Business, PlatSons, AgentCommu, Goods, GoodsSpec, Region,  Order, OrderGoods, Coupon,  Order as Orders};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;

class Shops extends Base
{

    protected $middleware = ['Sauth'];

    public function catelist()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'isshow' => 'require|in:1,2',

            ], [
                'name.require' => '名称不能为空',
                'isshow.require' => '类型不能为空',
                'isshow.in' => '类型不正确',

            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!empty($data['id'])) {
                $cate = (new PlatClass())->where(['businessid' => $this->request->shop['id'], 'id' => $data['id']])->find();
                if (empty($cate)) {
                    $this->result([], 1, '类别不存在');
                }
            }
            $save = ['businessid' => $this->request->shop['id'], 'id' => $data['id'], 'type' => 2, 'name' => $data['name'], 'isshow' => $data['isshow'], 'sort' => $data['sort']];
            Db::startTrans();
            try {
                if (!empty($data['id'])) {
                    (new PlatClass())->allowfield(true)->save($save, ['id' => $data['id']]);
                } else {
                    (new PlatClass())->allowfield(true)->save($save);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败，请重试');
            }
            $this->result([], 0, '操作成功');
        } else {
            $list = (new PlatClass())->order('isshow asc')->where(['businessid' => $this->request->shop['id'], 'type' => 2])->select();
            $this->result($list, 0, '查询完成');
        }
    }

    public function commulist()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'type' => 'require|in:1,2', //1删除 2申请
            ], [
                'id.require' => 'ID不能为空',
                'type.require' => 'type不能为空',
                'type.in' => 'type类型不正确',

            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if ($data['type'] == 2) {
                $bcommu = (new BusinessCommu())->where(['businessid' => $this->request->shop['id'], 'commuid' => $data['id']])->find();
                if (!empty($bcommu) && ($bcommu['status'] == 1 || $bcommu['status'] == 2)) {
                    $this->result([], 1, '已服务或申请中小区不可重复申请');
                }
            }
            Db::startTrans();
            try {
                if ($data['type'] == 1) {
                    (new BusinessCommu())->where(['businessid' => $this->request->shop['id'], 'id' => $data['id']])->delete();
                }
                if (!empty($bcommu)) {
                    (new BusinessCommu())->where(['businessid' => $this->request->shop['id'], 'commuid' => $data['id']])->update(['status' => 2]);
                } else {
                    (new BusinessCommu())->allowfield(true)->save(['businessid' => $this->request->shop['id'], 'commuid' => $data['id'], 'status' => 2]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败，请重试');
            }
            $this->result([], 0, '操作成功');
        } else {
            $type = $this->request->get('type/d', 1);
            $lat = $this->request->get('lat/d', 0);
            $lon = $this->request->get('lon/d', 0);
            $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
            if ($type == 1) {
                $list = (new BusinessCommu())->where(['businessid' => $this->request->shop['id']])->select();
                $result = [];
                foreach ($list as $row) {
                    $commu = (new AgentCommu())->field('id,name,address,' . $filed)
                        ->where('id', $row['commuid'])->find();
                    if (!empty($commu)) {
                        $result[] = [
                            'id' => $row['id'] ?? '',
                            'commuid' => $commu['id'] ?? '',
                            'status' => $row['status'] ?? '',
                            'name' => $commu['name'] ?? '',
                            'address' => $commu['address'] ?? '',
                            'dist' => $commu['dist'] ?? '',
                        ];
                    }
                }
            } else {
                $result = (new AgentCommu())
                    ->field('id,name,address,' . $filed)
                    ->limit(15)
                    ->order('dist asc')
                    ->where('status', 1)
                    ->select();
                foreach ($result as $row) {
                    $list = (new BusinessCommu())->where(['businessid' => $this->request->shop['id'], 'commuid' => $row['id']])->find();
                    if (empty($list)) {
                        $row['status'] = 0;
                    } else {
                        $row['status'] = $list['status'];
                    }
                }
            }

            $this->result($result, 0, '查询完成');
        }
    }

    public function moneylog()
    {
        $list = (new BussinessLog())->order('id desc');
        $list = $list->where(['user_id' =>  $this->request->shop['id']])
            ->field('info,money,created')
            ->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '查询完成');
    }

    public function shop_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'images' => 'require',
                'name' => 'require',
                'mobile' => 'require',
                'lat' => 'require',
                'lon' => 'require',
                'address' => 'require',
                'images1' => 'require',
                'images2' => 'require',
            ], [
                'title.require' => '名称不能为空',
                'images.require' => 'LOGO不能为空',
                'name.require' => '负责人姓名不能为空',
                'mobile.require' => '联系电话不能为空',
                'lat.require' => '坐标不能为空',
                'lon.require' => '坐标不能为空',
                'address.require' => '详细地址不能为空',
                'images1.require' => '店内环境不能为空',
                'images2.require' => '营业执照不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $save = [
                'title' => $data['title'] ?? '',
                'logo' =>  $data['images'] ?? '',
                'name' =>  $data['name'] ?? '',
                'mobile' =>  $data['mobile'] ?? '',
                'lat' =>  $data['lat'] ?? '',
                'lon' =>  $data['lon'] ?? '',
                'address' =>  $data['address'] ?? '',
                'images' => json_encode($data['images1']) ?? '',
                'yyzz' => json_encode($data['images2']) ?? '',
                'sends' =>  $data['sends'] ?? 0,
                'sendmoney' =>  $data['sendmoney'] ?? 0,
            ];
            Db::startTrans();
            try {
                (new Business())->allowfield(true)->save($save, ['id' => $this->request->shop['id']]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败，请重试');
            }
            $this->result([], 0, '操作成功');
        } else {
            $datas = [
                'type' => $this->request->shop['type'] ?? 0,
                'todyacount' => (new Orders())->whereTime('paytimes', '>=', date('Y-m-d'))->where(['businessid' => $this->request->shop['id'], 'status' => [2, 3, 4]])->count(),
                'todytotal' => (new Orders())->whereTime('paytimes', '>=', date('Y-m-d'))->where(['businessid' => $this->request->shop['id'], 'status' => [2, 3, 4]])->sum('total'),
                'yesacount' => (new Orders())->whereTime('paytimes', '<', date('Y-m-d'))->whereTime('paytimes', '>=', date('Y-m-d', time() - 86400))->where(['businessid' => $this->request->shop['id'], 'status' => [2, 3, 4]])->count(),
                'yestotal' => (new Orders())->whereTime('paytimes', '<', date('Y-m-d'))->whereTime('paytimes', '>=', date('Y-m-d', time() - 86400))->where(['businessid' => $this->request->shop['id'], 'status' => [2, 3, 4]])->sum('total'),
                'order' => (new Orders())->where(['businessid' => $this->request->shop['id'], 'status' => [2, 3, 4]])->count(),
                'total' => (new Orders())->where(['businessid' => $this->request->shop['id'], 'status' => [2, 3, 4]])->sum('total'),
            ];
            $this->result($datas, 0, '获取成功');
        }
    }

    public function getshop()
    {
        $shop = $this->request->shop;
        $shop['images'] = json_decode($shop['images'], true) ?? [];
        $shop['yyzz'] = json_decode($shop['yyzz'], true) ?? [];
        $shop['password'] = '';
        $this->result($shop, 0, '获取成功');
    }

    public function goods_static()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'type' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'type.require' => '类型不能为空',

            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //1上下架 2规格删除
            if ($data['type'] == 1) {
                $goods = (new Goods())->where(['id' => $data['id'], 'businessid' => $this->request->shop['id']])->find();
                if (empty($goods)) {
                    $this->result([], 1, '产品不存在');
                }
                $status = $goods['isSale'] == 1 ? 2 : 1;
            } elseif ($data['type'] == 2) {
                $goodsspec = (new GoodsSpec())->where(['id' => $data['id'], 'businessid' => $this->request->shop['id']])->find();
                if (empty($goodsspec)) {
                    $this->result([], 1, '规格不存在');
                }
                $goodspecs =  (new GoodsSpec())->where(['goodid' => $goodsspec['goodid'], 'businessid' => $this->request->shop['id'], 'isdel' => 1])->count();
                if ($goodspecs <= 1) {
                    $this->result([], 1, '商品必须保留一个规格，如需删除请先提交新规格保存后删除');
                }
            } else {
                $this->result([], 1, '类型错误');
            }

            Db::startTrans();
            try {
                if ($data['type'] == 1) {
                    (new Goods())->where('id', $data['id'])->update(['isSale' => $status]);
                }
                if ($data['type'] == 2) {
                    (new GoodsSpec())->where('id', $data['id'])->update(['isdel' => 2]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败，请重试');
            }
            $this->result([], 0, '操作成功');
        }
    }

    public function goods_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'images' => 'require',
                'classid' => 'require',
                'sonsid' => 'require',
                'spec' => 'require'
            ], [
                'title.require' => '产品名称不能为空',
                'images.require' => '图片不能为空',
                'classid.require' => '分类不能为空',
                'sonsid.require' => '子分类不能为空',
                'spec.require' => '规格必须填写'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!empty($data['images'])) {
                $images = $data['images'] ?? [];
                $imageslist = [];
                foreach ($images as $image) {
                    $imageslist[] =  $image['url'] ?? '';
                }
            }
            if (count($imageslist) < 1) {
                $this->result([], 1, '封面图不能低于1张');
            }
            if (empty($data['spec']) || count($data['spec']) <= 0) {
                $this->result([], 1, '规格信息不能少于一个');
            }
            $save = [
                'title' => $data['title'],
                'businessid' => $this->request->shop['id'],
                'classid' => $data['classid'],
                'sonsid' => $data['sonsid'],
                'images' => json_encode($imageslist, true) ?? '',
                'starbuy' => $data['starbuy']  < 1 ? 1 : $data['starbuy'],
                'times' => $data['times'] ?? 60,
                'descs' => $data['descs'],
                'goodsDesc' => $data['goodsDesc'],
            ];
            $speclist = [];
            foreach ($data['spec'] as $spec) {
                if (empty($spec['name']) || empty($spec['unmit'])) {
                    $this->result([], 1, '规格名或单位不能为空');
                }
                $speclist[] = [
                    'id' => $spec['id'] ?? 0,
                    'name' => $spec['name'] ?? '',
                    'price' => $spec['price'] ?? 0,
                    'unmit' => $spec['unmit'] ?? '',
                    'is_default' => $spec['is_default'] ?? 0,
                ];
            }
            if (!empty($data['id'])) {
                $goods = (new Goods())->where(['id' => $data['id'], 'businessid' => $this->request->shop['id']])->find();
                if (empty($goods)) {
                    $this->result([], 1, '产品不存在');
                }
            }
            Db::startTrans();
            try {
                if (empty($data['id'])) {
                    $data['id'] = (new Goods())->insertGetid($save);
                } else {
                    (new Goods())->allowfield(true)->save($save, ['id' => $data['id']]);
                }
                foreach ($speclist as $spec) {
                    if (!empty($spec['id'])) {
                        (new GoodsSpec())->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                    } else {
                        unset($spec['id']);
                        $spec['businessid'] = $this->request->shop['id'];
                        $spec['goodid'] =  $data['id'];
                        (new GoodsSpec())->allowfield(true)->save($spec);
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败，请重试');
            }
            $this->result([], 0, '操作成功');
        }
    }

    public function orderstatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'status' => 'require|in:3,4,5'
        ], [
            'id.require' => '订单ID不能为空',
            'status.require' => '状态不能为空',
            'status.in' => '状态不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where(['id' => $data['id'], 'businessid' => $this->request->shop['id']])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        switch ($data['status']) {
            case '3':
                if ($order['status'] != 2) {
                    $this->result([], 1, '订单状态不可接单');
                }
                //完成订单
                $res = (new Order())->where('id', $data['id'])->update(['status' => $data['status'], 'fwtimes' => date('Y-m-d H:i:s')]);
                if ($res) {
                    $this->result([], 0, '操作成功');
                }

                $this->result([], 1, '操作失败，请重试');
                break;
            case '4':
                if ($order['status'] != 3) {
                    $this->result([], 1, '订单状态不可完成');
                }
                //完成订单
                $res = (new Order())->where('id', $data['id'])->update(['status' => $data['status'], 'finishtimes' => date('Y-m-d H:i:s')]);
                if ($res) {
                    $this->result([], 0, '操作成功');
                }
                $this->result([], 1, '操作失败，请重试');
                break;
            case '5':
                if ($order['status'] != 1 && $order['status'] != 2) {
                    $this->result([], 1, '订单状态不可取消');
                }
                if ($order['shouhou'] != 1) {
                    $this->result([], 1, '订单处于售后状态或已售后');
                }
                //取消
                if ($order['status'] == 1 || $order['status'] == 2) {
                    $shouhou = 1;
                    $status = $data['status'];
                    $tuikuan = 0;
                    $msg = '取消成功';
                    if ($order['status'] == 2 && $order['total'] > 0) {
                        $shouhou = 2;
                        $status = $order['status'];
                        $msg = '订单已提交';
                        $tuikuan = 2;
                    }
                    Db::startTrans();
                    try {
                        if ($order['coupon'] > 0 && $status == 5) {
                            (new Coupon())->where('id', $order['coupon'])->update(['status' => 1]);
                        }
                        (new Order())->where('id', $data['id'])->update([
                            'status' => $status,
                            'text' => $data['text'] ?? '',
                            'shouhou' => $shouhou,
                            'tuikuan' => $tuikuan,
                            'caceltimes' => date('Y-m-d H:i:s')
                        ]);
                        Db::commit();
                        if ($order['status'] == 2 && $order['total'] > 0) {
                            Redis::lPush('tuikuan', $order['id']);
                        }
                    } catch (\Exception $e) {
                        dump($e->getMessage());
                        Db::rollback();
                        $this->result([], 1, '操作失败，请重试');
                    }
                    $this->result([], 0, $msg);
                }
                break;
            default:
                $this->result([], 1, '状态出错');
                break;
        }
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where('id', $id)->field('putorder,coupon,paytimes,fwtimes,finishtimes,caceltimes', true)->find();
        if ($list) {
            $list['images'] = json_decode($list['images'] ?? '', true) ?? [];
            $list['leimu_name'] = (new PlatSons())->where('id', $list['leimu'])->value('name') ?? '';
            $list['xiaoquaddress'] = (new AgentCommu())->where('id', $list['xiaoquid'])->value('address') ?? '';
            $list['status_text'] = $list->status_text;
            $list['province_text'] = (new Region())->where(['area_code' => $list['province']])->value('name');
            $list['city_text'] = (new Region())->where(['area_code' => $list['city']])->value('name');
            $list['area_text'] = (new Region())->where(['area_code' => $list['area']])->value('name');
            $list['street_text'] = (new Region())->where(['id' => $list['street']])->value('name');
            $goods = (new OrderGoods())->where('ordersn', $list['ordersn'])->field('id,ordersn,images,number,title,name,goodsid,goodspecid,price,unmit,iscompent')->select();
            foreach ($goods as $good) {
                $good['images'] = json_decode($good['images'], true);
            }
            $list['good'] = $goods;
        }
        $this->result($list, 0, '获取成功');
    }

    public function orderlist()
    {
        $status = $this->request->get('status/d', '');
        $list = (new Order())->order('id desc')->where(['status' => [2, 3, 4, 5]]);
        if (!empty($status)) {
            $list = $list->where('status', $status);
        } else {
            $list = (new Order())->order('id desc')->where(['status' => [2, 3, 4]]);
        }
        $business = $this->request->shop;
        $list = $list->where('businessid', $business['id'])->field('id,leimu,images,xiaoquid,putaddress,sendaddress,qusong,types,ordertype,ordersn,businessid,status,total,ptotal,shouhou,tuikuan,created,ispj,payment')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['tnumber'] = 0;
            $ordergoods = (new OrderGoods())->where(['ordersn' => $lists['ordersn']])->field('id,title,name,unmit,goodspecid,images,number,iscompent,price')->select();
            foreach ($ordergoods as $goods) {
                $lists['tnumber'] += $goods['number'];
                $goods['images'] = json_decode($goods['images'] ?? '', true);
            }
            $lists['goods'] = $ordergoods;
            $lists['status_text'] = $lists->status_text;
            $lists['images'] = json_decode($lists['images'], true) ?? [];
            $lists['leimu_name'] = (new PlatSons())->where('id', $lists['leimu'])->value('name') ?? '';
            $lists['xiaoquaddress'] = (new AgentCommu())->where('id', $lists['xiaoquid'])->value('address') ?? '';
        }
        $this->result($list, 0, '获取成功');
    }
}
